package cn.superlu.onlyoffice.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

@RestController
@RequestMapping("/onlyoffice")
@Slf4j
public class OnlyOfficeController {

    /**
     * 回调
     */
    @RequestMapping("/callback")
    public String callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";

        JSONObject jsonObj = JSONObject.parseObject(body);
        System.out.println(jsonObj.get("status"));
        if((int) jsonObj.get("status") == 2)
        {
            String downloadUri = (String) jsonObj.get("url");
            URL url = new URL(downloadUri);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            InputStream stream = connection.getInputStream();
            String fileName = cn.hutool.core.lang.UUID.randomUUID().toString().replace("-", "") + "_create." + jsonObj.get("filetype");
            String templatePath = getClass().getClassLoader().getResource("").getPath();
            templatePath += fileName;
            log.info("文件保存地址：" + templatePath);
            File tempFile = new File(templatePath);
            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                int read;
                final byte[] bytes = new byte[1024];
                while ((read = stream.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
                out.flush();
            }
            connection.disconnect();
        }
        return "{\"error\":0}";
    }
}
